package controllers

import java.io.File
import java.nio.file.Files

import config.{Global, MyFile}
import javax.inject.Inject
import play.api.mvc.{AbstractController, ControllerComponents, Headers}

import scala.concurrent.ExecutionContext

class ImageController @Inject()(cc: ControllerComponents)(implicit exec: ExecutionContext) extends AbstractController(cc) with MyFile {

  def getPhoto(num: String) = Action { implicit request =>
    val file = s"${Global.path}/img/${num}.png".toFile
    SendImg(file, request.headers)
  }

  def getMediumPhoto(code: String, num: String) = Action { implicit request =>
    val file = s"${Global.path}/images/${code}_${num}_medium.jpg".toFile
    SendImg(file, request.headers)
  }

  def getMaxPhoto(code: String, num: String) = Action { implicit request =>
    val file = s"${Global.path}/images/${code}_${num}.jpg".toFile
    SendImg(file, request.headers)
  }

  def getQtlImg(name: String, chr: String) = Action { implicit request =>
    val i = name.last
    val file = s"${Global.path}/QTL/$name/QTL$i.$chr.png"
    SendImg(file.toFile, request.headers)
  }

  def SendImg(file: File, headers: Headers) = {
    val f = if (!file.exists()) {
      s"${Global.path}/null.jpg".toFile
    } else {
      file
    }

    val lastModifiedStr = f.lastModified().toString
    val MimeType = "image/jpg"
    val byteArray = Files.readAllBytes(f.toPath)
    val ifModifiedSinceStr = headers.get(IF_MODIFIED_SINCE)
    if (ifModifiedSinceStr.isDefined && ifModifiedSinceStr.get == lastModifiedStr) {
      NotModified
    } else {
      Ok(byteArray).as(MimeType).withHeaders(
        LAST_MODIFIED -> f.lastModified().toString
      )
    }
  }

}
